<template>
  <div>
    <div>
      <ele-page
        v-loading="loading"
        :formConfig="searchDialog"
        ref="eleTable"
        :operateList="operateList"
        @handleOperateEvent="handleOperateEvent"
        :column="column"
        :getList="getListNew"
        :otherParams="{
          orderStatusInList: '1,2,3,4,7',
          reportWay: 'report_way_unique',
        }"
        uniqueId="mesPrintProdOrder"
      >
      </ele-page>
    </div>
    <ele-form-drawer
      :isLoading="isLoading"
      v-model="formDataDialog"
      v-bind="formDescDialog"
      :request-fn="handleSubmit"
      :visible.sync="visible"
      :title="title"
    >
    </ele-form-drawer>

    <!-- 模态框 -->
    <barcodePrintingAddModel
      ref="barcodePrintingAddModel"
      :title="modelTitle"
      @refreshList="getListArr()"
    >
    </barcodePrintingAddModel>

    <!-- 补打模态框 -->
    <repairPrintModel
      ref="repairPrintModel"
      @refreshList="getListArr()"
    ></repairPrintModel>

    <!-- 生码 -->
    <el-dialog
      width="60%"
      :title="createTitle"
      :visible.sync="createVisible"
      :append-to-body="true"
      @close="clearCreateDialog()"
      v-loading="loading"
      :close-on-click-modal="false"
    >
      <ele-form v-model="createData" v-bind="createFormConfig" ref="form">
      </ele-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="clearCreateDialog()">{{
          $t("common.cancel")
        }}</el-button>
        <el-button type="primary" @click="handleCreate">{{
          $t("common.submit")
        }}</el-button>
      </div>
    </el-dialog>
    <repairPrintTable ref="repairPrintTables"></repairPrintTable>

    <!-- 清除箱码备注提交弹窗 -->
    <ele-form-drawer
      ref="notesFormData"
      width="400px"
      v-model="remarkForm"
      :formDesc="{
        remark: {
          type: 'textarea',
          label: $i18n.t('mesUniqueCodePrinting.remark2'),
          layout: 24,
          required: true,
        },
      }"
      :request-fn="clearBarcode"
      :visible.sync="notesdialogFormVisible"
      :title="$i18n.t('mesUniqueCodePrinting.remind')"
    ></ele-form-drawer>
  </div>
</template>

<script>
import { operateList, searchConfig, formDescDialog } from "./config";
import {
  getList,
  getListNew,
  rowCreate,
  rowUpdate,
  rowDel,
  getInfo,
  getProdOrderStatusList,
  getPrepositionTypeList,
  getGenCount,
} from "@/api/print/mesProdOrder";
import {
  selectCommonProduceRelByProduce,
  genCodeBatch,
  clearBoxcode,
  getBoxCount,
  selectListByConfigurationCode,
} from "@/api/print/mesProdBarcodePrint";
import barcodePrintingAddModel from "./components/barcodePrintingAddModel";
import { popover } from "@/utils/judge";
import repairPrintModel from "./components/repairPrintModel.vue";
import repairPrintTable from "./components/repairPrintTable.vue";
export default {
  name: "mesPrintProdOrder",
  components: {
    barcodePrintingAddModel,
    repairPrintModel,
    repairPrintTable,
  },
  mixins: [searchConfig],
  data() {
    const _this = this;
    return {
      remarkForm: {},
      modelTitle: "",
      notesdialogFormVisible: false,
      title: null,
      visible: false,
      isLoading: false,
      loading: false,
      formDataDialog: {},
      formDescDialog, //新增修改框
      // searchConfig,
      operateList,
      getListNew,
      createTitle: _this.$i18n.t("mesUniqueCodePrinting.create"),
      createVisible: false,
      maxNum: 9999,
      createData: {
        orderCode: null,
        goodsCode: null,
        codeStrategy: null,
        amount: 0,
      },
      // 列表页字段的绑定配置
      column: [
        {
          type: "selection",
        },
        {
          type: "index",
          label: $i18n.t("common.order"),
          width: 60,
          fixed: "left",
        },
        {
          prop: "planCode",
          label: $i18n.t("mesUniqueCodePrinting.planCode"),
          fixed: "left",
          minWidth: 180,
          showOverflowTooltip: true,
        },
        {
          prop: "orderCode",
          label: $i18n.t("mesUniqueCodePrinting.orderCode"),
          fixed: "left",
          minWidth: 240,
          // showOverflowTooltip: true,
          render: (h, scope) => {
            return popover(scope.row.orderCode, h, "", () =>
              _this.goChild({ orderCode: scope.row.orderCode })
            );
          },
        },

        {
          prop: "prodCode",
          label: $i18n.t("mesUniqueCodePrinting.prodCode"),
          minWidth: 130,
          showOverflowTooltip: true,
        },
        {
          prop: "prodName",
          label: $i18n.t("mesUniqueCodePrinting.prodName"),
          minWidth: 130,
          showOverflowTooltip: true,
        },
        {
          prop: "quantity",
          label: $i18n.t("mesUniqueCodePrinting.planQuantity"),
          minWidth: 110,
          showOverflowTooltip: true,
        },
        {
          prop: "actualQuantity",
          label: $i18n.t("mesUniqueCodePrinting.actualQuantity"),
          minWidth: 120,
          showOverflowTooltip: true,
        },
        {
          prop: "barcodeCreateCount",
          label: $i18n.t("mesUniqueCodePrinting.barcodeCreateCount"),
          minWidth: 120,
          showOverflowTooltip: true,
        },
        {
          prop: "barcodePrintCount",
          label: $i18n.t("mesUniqueCodePrinting.barcodePrintCount"),
          minWidth: 120,
          showOverflowTooltip: true,
        },
        {
          prop: "orderStatus",
          label: $i18n.t("mesUniqueCodePrinting.orderStatus"),
          minWidth: 140,
          showOverflowTooltip: true,
          optionProp: {
            value: "value",
            label: "description",
          },
          option: async (data) => {
            const list = await getProdOrderStatusList();
            return list.data.result;
          },
        },

        {
          prop: "planBeginDate",
          label: $i18n.t("mesUniqueCodePrinting.planBeginDate"),
          minWidth: 130,
          showOverflowTooltip: true,
        },

        {
          prop: "workshopName",
          label: $i18n.t("common.workshopName"),
          minWidth: 150,
        },
        {
          prop: "lineName",
          label: $i18n.t("common.lineName"),
          minWidth: 150,
          showOverflowTooltip: true,
        },
        {
          prop: "unit",
          label: $i18n.t("mesUniqueCodePrinting.measureUnit"),
          minWidth: 110,
          showOverflowTooltip: true,
        },
        {
          prop: "unitCode",
          label: $i18n.t("mesUniqueCodePrinting.measureUnitCode"),
          minWidth: 140,
          showOverflowTooltip: true,
        },
        // {
        //   prop: "deliveryDate",
        //   label: $i18n.t("printBoxCode.deliveryDate"),
        //   minWidth: 140,
        //   showOverflowTooltip: true
        // },
        // {
        //   prop: "slackTime",
        //   label: $i18n.t("printBoxCode.slackTime"),
        //   minWidth: 180,
        //   showOverflowTooltip: true
        // },
        // {
        //   prop: "prepositionCode",
        //   label: $i18n.t("printBoxCode.prepositionCode"),
        //   minWidth: 120,
        //   showOverflowTooltip: true
        // },
        // {
        //   prop: "prepositionType",
        //   label: $i18n.t("printBoxCode.prepositionType"),
        //   minWidth: 120,
        //   showOverflowTooltip: true,
        //   optionProp: {
        //     value: "value",
        //     label: "description"
        //   },
        //   option: async (data) => {
        //     const list = await getPrepositionTypeList()
        //     return list.data.result
        //   }
        // }
        // {
        //   prop: "operate",
        //   label: "操作",
        //   width: 160,
        //   fixed: "right",
        //   render: (h, scope) => {
        //     return (
        //       <ele-row-operation
        //         scope={scope}
        //         rowConfig={rowConfig}
        //         onRowOperate={this.rowOperate}
        //       ></ele-row-operation>
        //     );
        //   },
        // },
      ],
      createFormConfig: {
        span: 24,
        isShowBackBtn: false,
        isShowSubmitBtn: false,
        labelPosition: "right",
        formDesc: {
          orderCode: {
            type: "input",
            label: _this.$i18n.t("mesUniqueCodePrinting.orderCode"),
            layout: 12,
            disabled: true,
          },
          goodsCode: {
            type: "input",
            label: _this.$i18n.t("mesUniqueCodePrinting.prodCode"),
            layout: 12,
            disabled: true,
          },
          codeStrategy: {
            type: "select",
            label: _this.$i18n.t("mesUniqueCodePrinting.codeStrategy"),
            layout: 12,
            prop: {
              value: "codeStrategyCode",
              text: "codeStrategyDescription",
            },
            options: async (data) => {
              const params = {
                goodsCode: data.goodsCode,
                templateType: "unique_code",
                type: "codeStrategy",
              };
              const list = await selectCommonProduceRelByProduce(params);
              return list.data.result;
            },
            required: true,
            disabled: false,
          },
          amount: {
            type: "number",
            label: _this.$i18n.t("mesUniqueCodePrinting.genCount"),
            layout: 12,
            required: true,
            attrs: {
              stepStrictly: true,
              min: 1,
              max: _this.maxNum,
            },
          },
        },
      },
    };
  },
  computed: {},
  methods: {
    getListArr() {
      //this.$refs.barcodePrintingAddModel.visible = false;
      this.refresh(false);
    },
    //表格顶部按钮操作事件
    handleOperateEvent({ handleName, name, rows }) {
      this.title = name;
      let _this = this;
      const fnc = {
        add: () => {
          this.changeMaster(false);
          this.formDataDialog = {};
          this.visible = true;
        },
        // delete: () => {
        //   this.$confirm("此操作将删除该生产工单, 是否继续?", "提示", {
        //     confirmButtonText: "确定",
        //     cancelButtonText: "取消",
        //     type: "warning",
        //   }).then(() => {
        //     const ids = rows.map((val) => val.id).join(",");
        //     this.rowDel(ids);
        //   });
        // },
        // 点击生码按钮
        getGenCount() {
          _this.showCreate(rows[0]);
        },
        printBoxCode: () => {
          // if (rows[0].isCreateBarcode === "0") {
          //   this.$confirm(this.$i18n.t("printBoxCode.isCreateBarcode"), this.$i18n.t("common.tip"), {
          //     confirmButtonText: this.$i18n.t("common.ok"),
          //     cancelButtonText: this.$i18n.t("common.cancel"),
          //     type: "warning"
          //   }).then(() => {
          //     _this.showCreate(rows[0])
          //   })
          // } else {
          // 打印唯一码
          this.modelTitle = name;
          this.$refs.barcodePrintingAddModel.init({
            ...rows[0],
          });
          // }
        },
        // 清除唯一码
        clearBarcode: () => {
          if (rows[0].isCreateBarcode === "0") {
            this.$message.warning(
              this.$i18n.t("mesUniqueCodePrinting.canNotClearUniqueCode")
            );
            return;
          }
          _this.notesdialogFormVisible = true;

          _this.remarkForm = rows[0];
          // _this.clearBarcode(rows[0]);
        },
        repairPrint: () => {
          this.repairPrint(rows[0]);
        },
      };
      fnc[handleName] && fnc[handleName]();
    },
    //表格行操作事件
    rowOperate({ handleName, name, row }) {
      this.title = name;
      const fnc = {
        show: () => {
          // 查看详情，并打开界面
          this.editInfo(row.id, true);
        },
        edit: () => {
          // 修改详情，并打开界面
          this.editInfo(row.id, false);
        },
        multiAdd: () => {
          this.goMultiAdd({ id: row.id });
        },
      };
      fnc[handleName] && fnc[handleName]();
    },
    //弹框提交事件
    handleSubmit(data) {
      if (this.isLoading) return; // 判断状态
      this.isLoading = true;
      this.formDataDialog.id ? this.rowUpdate(data) : this.rowCreate(data);
    },

    // 补打判断
    async repairPrint(list) {
      let { workshopCode, lineCode, orderCode, barcodePrintTemp } = list;
      if (!barcodePrintTemp) {
        this.$message.warning($i18n.t("mesUniqueCodePrinting.uniqueCodeForMessage"));
        return;
      }
      let data = {
        configurationCode: "com_unique_code_reviewed",
        levelType: "5",
      };
      if (lineCode) {
        data.levelType = "5";
        data.lineCode = lineCode;
      } else {
        data.levelType = "4";
        data.workshopCode = workshopCode;
      }
      let res1 = await getBoxCount({
        orderCode,
      });
      let { quantityPrinted } = res1.data.result;
      if (quantityPrinted <= 0) {
        this.$message.warning(
          $i18n.t("mesUniqueCodePrinting.dataThatCannotBeMadeUpYet")
        );
        return;
      }
      this.loading = true;
      let res = await selectListByConfigurationCode(data);
      let { result } = res.data;
      this.loading = false;
      let bool = false; //true 需要审核  false 不需要审核
      if (result && result.length) {
        if (result[0].value == "1") {
          bool = true;
        }
      }
      if (bool) {
        this.$refs.repairPrintTables.init({
          ...list,
          isPrint: 0,
        });
      } else {
        // 补打已打印唯一码
        this.$refs.repairPrintModel.init({
          ...list,
          barcodePrintTemp: list.barcodePrintTemp,
          quantity: 0,
        });
      }
    },

    //新增
    rowCreate(data) {
      rowCreate(data)
        .then((res) => {
          const message = res.data.message;
          this.$message.success(
            message || $i18n.t("common.addSuccess")
          );
          this.visible = false;
          this.refresh();
        })
        .finally(() => {
          this.isLoading = false;
        });
    },
    // 修改详情
    editInfo(id, flag) {
      this.changeMaster(flag);
      this.loading = true;
      getInfo(id)
        .then((res) => {
          this.formDataDialog = res.data.result;
          this.visible = true;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    //修改
    rowUpdate(data) {
      rowUpdate(data)
        .then((res) => {
          const message = res.data.message;
          this.$message.success(message || $i18n.t("common.editSuccess"));
          this.visible = false;
          this.refresh();
        })
        .finally(() => {
          this.isLoading = false;
        });
    },
    //删除
    rowDel(data) {
      this.loading = true;
      rowDel(data)
        .then((res) => {
          const message = res.data.message;
          this.$message.success(message || $i18n.t("common.deleteSuccess"));
          this.refresh();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    //刷新表格数据
    refresh(isReset = true) {
      this.$refs.eleTable.refresh(isReset);
    },
    //跳转至子页面
    goChild(queryParam) {
      let pathParam = "/print/mesUniqueCode";
      this.$router.push({ path: pathParam, query: queryParam });
    },
    // 跳转至批量新增页面
    goMultiAdd(queryParam) {
      let pathParam = "/print/mesProdOrderAdd";
      this.$router.push({ path: pathParam, query: queryParam });
    },
    changeMaster(flag) {
      if (flag) {
        formDescDialog.disabled = true;
        formDescDialog.isShowSubmitBtn = false;
      } else {
        formDescDialog.disabled = false;
        formDescDialog.isShowSubmitBtn = true;
      }
    },
    clearCreateDialog() {
      this.createVisible = false;
      this.createData.amount = 0;
      this.maxNum = 9999;
      this.createData.codeStrategy = null;
      this.createFormConfig.formDesc.codeStrategy.disabled = false;
    },
    showCreate(data) {
      // 查询工单可生码数量
      this.loading = true;
      console.log(data.id);
      getGenCount(data.id)
        .then((res) => {
          if (res.data.success) {
            const maxNum = res.data.result;
            console.log(maxNum);
            if (maxNum === 0) {
              this.$message.warning(this.$i18n.t("mesUniqueCodePrinting.allGen"));
            } else {
              this.createVisible = true;
              this.createData.orderCode = data.orderCode;
              this.createData.goodsCode = data.prodCode;
              this.createData.amount = maxNum;
              this.createFormConfig.formDesc.amount.attrs.max = maxNum;
              if (data.orderBarcodeRuleCode) {
                this.createData.codeStrategy = data.orderBarcodeRuleCode;
                this.createFormConfig.formDesc.codeStrategy.disabled = true;
              }
            }
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    handleCreate() {
      this.$refs.form.validate().then((valid) => {
        const data = {
          orderCode: this.createData.orderCode,
          codeStrategy: this.createData.codeStrategy,
          amount: this.createData.amount,
        };
        this.loading = true;
        genCodeBatch(data)
          .then((res) => {
            if (res.data.success) {
              const message = res.data.message;
              this.$message.success(
                message || this.$i18n.t("mesUniqueCodePrinting.createSuccess")
              );
              this.clearCreateDialog();
              this.refresh();
            } else {
              this.$message.warning(res.data.message);
            }
          })
          .finally(() => {
            this.loading = false;
          });
      });
    },
    async clearBarcode(data) {
      try {
        if (data.isCreateBarcode === "0") {
          this.$message.warning(
            this.$i18n.t("mesUniqueCodePrinting.canNotClearUniqueCode")
          );
          return;
        } else {
          this.loading = true;
          const res = await clearBoxcode({
            clearReason: data.remark,
            orderCode: data.orderCode,
          });
          if (res.data.success) {
            this.$message.success(
              this.$i18n.t("mesUniqueCodePrinting.clearBarcodeSuccess")
            );
          }
          this.notesdialogFormVisible = false;
          this.refresh();
        }
      } catch (error) {
      } finally {
        this.loading = false;
      }
    },
  },
};
</script>
